package core

import (
	"crypto/sha256"
	"encoding/hex"
	"time"
)

type Block struct {
	Index        int64  // 区块编号
	Timestamp    int64  // 区块时间戳
	PreBlockHash string // 上个区块哈希值
	Hash         string // 当前区块哈希值
	Data         string // 区块数据
}

// 计算Hash值
func calculateHash(b Block) string {
	blockData := string(b.Index) + string(b.Timestamp) + b.PreBlockHash + b.Data
	hashInBytes := sha256.Sum256([]byte(blockData))
	return hex.EncodeToString(hashInBytes[:])

}

// 生成区块
func GenerateNewBlock(preBlock Block, data string) Block {
	newBlock := Block{}
	newBlock.Index = int64(preBlock.Index + 1)
	newBlock.PreBlockHash = preBlock.Hash
	newBlock.Data = data
	newBlock.Timestamp = int64(time.Now().Unix())
	newBlock.Hash = calculateHash(newBlock)
	return newBlock
}

// 原始区块
func GenerateGenesisBlcok() Block {
	preBlock := Block{}
	preBlock.Index = -1
	preBlock.Hash = ""
	return GenerateNewBlock(preBlock, "Genesis Block")
}
